package com.wanyangproject.shouye;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.entity.ChanYeJinRongXiangQingEntity;
import com.wanyangproject.entity.FenXiangShiBaiEntity;
import com.wanyangproject.entity.PanDuanShouCangEntity;
import com.wanyangproject.entity.WenZhangChanYeJinRongEntity;
import com.wanyangproject.entity.WenZhangShouCangEntity;
import com.wanyangproject.entity.ZhaoPinFenXiangEntity;
import com.wanyangproject.entity.ZhiNengZhiZaoXiangQingEntity;
import com.wanyangproject.my.ZhaoPinXiangQingActivity;
import com.wanyangproject.popuwindow.SharePopupWindow;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.WebViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ZhiNengZhiZaoXiangQingActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.image_shoucang)
    ImageView imageShoucang;
    @BindView(R.id.image_fenxiang)
    ImageView imageFenxiang;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.webView)
    WebView webView;
    private String wenzhangid;
    private ChanYeJinRongXiangQingEntity chanYeJinRongXiangQingEntity;
    private WebSettings mWebSettings;
    private String content;
    private SharePopupWindow sharePopupWindow;
    private ProgressDialog progressDialog;
    private static Boolean isOK = false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhi_neng_zhi_zao_xiang_qing);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        wenzhangid = intent.getStringExtra("wenzhangid");
        System.out.println(wenzhangid + "    接收的文章id");


        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);  //允许加载javascript
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        mWebSettings.setSupportZoom(false);     //允许缩放
        mWebSettings.setBuiltInZoomControls(false); //原网页基础上缩放
        mWebSettings.setUseWideViewPort(false);   //任意比例缩放
//        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

//        智能制造详情的网络请求
        initZhiNengZhiZaoXiangQingHttp();



//
////        我的收藏文章收藏的网络请求
//        initMyShouCangHttp();


//        判断是否收藏过的文章
        initShiFouShouCangHttp();


        initView();
    }









    //    是否收藏过文章的网络请求
    private void initShiFouShouCangHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"news/shoucangjil")
                .addHeader("token",ContractUtils.getTOKEN(ZhiNengZhiZaoXiangQingActivity.this))
                .addParams("id",wenzhangid)
                .addParams("typeId","1")//0 园区手册   1 智能制造   2 产业金融   3 园区资讯   4 政策法规    5企服中心    6 园区招商
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e+"      eeeeeee 智能制造是否收藏过文章的");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"        只能制造是否收藏过文章的网络请求 ");
                        ContractUtils.Code500(ZhiNengZhiZaoXiangQingActivity.this,response);
                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            PanDuanShouCangEntity panDuanShouCangEntity = gson.fromJson(response, PanDuanShouCangEntity.class);
                            if(panDuanShouCangEntity.getResponse().getType().equals("1")){// 1 收藏    2 未收藏
                                imageShoucang.setImageResource(R.drawable.quxia_shoucang);
                            }else if(panDuanShouCangEntity.getResponse().getType().equals("2")){
                                imageShoucang.setImageResource(R.drawable.shoucang);
                            }

                        }
                    }
                });
    }







    //    我的收藏文章收藏的网络请求
    private void initMyShouCangHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"user/myShoucang")
                .addHeader("token",ContractUtils.getTOKEN(ZhiNengZhiZaoXiangQingActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e+"         我的收藏文章eeeeeee ");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"           我的收藏文章收藏的网络请求 ");
                        ContractUtils.Code500(ZhiNengZhiZaoXiangQingActivity.this,response);

                        if(response.indexOf("200") != -1) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                JSONArray response1 = jsonObject.getJSONArray("response");

                                Boolean isOK = false;
                                if(response1 != null){
                                    for (int i = 0; i < response1.length(); i++) {
                                        JSONObject json = (JSONObject) response1.get(i);
                                        if(json.getString("0").equals(wenzhangid)){
                                            isOK = true;
                                        }
                                    }

                                    if(isOK == true){
                                        imageShoucang.setImageResource(R.drawable.quxia_shoucang);
                                    }

                                }



                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }













    //    智能制造分享的网络请求
    private void initZhiNengZhiZaoHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"news/share")
                .addHeader("token",ContractUtils.getTOKEN(ZhiNengZhiZaoXiangQingActivity.this))
                .addParams("id",wenzhangid)
                .addParams("typeId","1")//0 =>园区手册1 => 智能制造2=>产品金融 3首页园区资讯, 4 政策法规, 5企服中心, 6园区招商
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"       智能制造分享的网络请求");
                        ContractUtils.Code500(ZhiNengZhiZaoXiangQingActivity.this,response);
                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            ZhaoPinFenXiangEntity zhaoPinFenXiangEntity = gson.fromJson(response, ZhaoPinFenXiangEntity.class);
                            Object itemsOnClick = null;
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.loginbaibian);
                            sharePopupWindow = new SharePopupWindow(ZhiNengZhiZaoXiangQingActivity.this,(View.OnClickListener) itemsOnClick,zhaoPinFenXiangEntity.getResponse().getTitle(),zhaoPinFenXiangEntity.getResponse().getUrl(),bitmap);
                            sharePopupWindow.showAtLocation(findViewById(R.id.relative_Layout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            FenXiangShiBaiEntity fenXiangShiBaiEntity = gson.fromJson(response, FenXiangShiBaiEntity.class);
                            Toast.makeText(ZhiNengZhiZaoXiangQingActivity.this, fenXiangShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void initView() {
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截 url 跳转,在里边添加点击链接跳转或者操作
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return WebViewUtils.shouldOverrideUrlLoading(view,request,ZhiNengZhiZaoXiangQingActivity.this);
            }



            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("66666666666666666666");
                return WebViewUtils.shouldOverrideUrlLoading(view,url,ZhiNengZhiZaoXiangQingActivity.this);

            }




            /**
             * 在开始加载网页时会回调
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("111111111111111111");
            }

            /**
             * 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }


            /**
             * 在结束加载网页时会回调
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("chenggongchenggongchenggong");
                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }

            /**
             * 当接收到https错误时，会回调此函数，在其中可以做错误处理
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            /**
             * 在每一次请求资源时，都会通过这个函数来回调
             */
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }


            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }
        });
    }













    //    智能制造详情的网络请求
    public void initZhiNengZhiZaoXiangQingHttp() {
        progressDialog = new ProgressDialog(ZhiNengZhiZaoXiangQingActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "news/getDetail")
                .addHeader("token", ContractUtils.getTOKEN(ZhiNengZhiZaoXiangQingActivity.this))
                .addParams("id", wenzhangid)
                .addParams("nTypeId", "1")//nTypeId智能制造传1  //nTypeId产业金融传2
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ZhiNengZhiZaoXiangQingActivity.this,response);
                        System.out.println(response + "    智能制造详情的网络请求");

                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            ZhiNengZhiZaoXiangQingEntity zhiNengZhiZaoXiangQingEntity = gson.fromJson(response, ZhiNengZhiZaoXiangQingEntity.class);
                            if (zhiNengZhiZaoXiangQingEntity.getResponse().getTitle() == null) {

                            } else { // 标题
                                tvTitle.setText(zhiNengZhiZaoXiangQingEntity.getResponse().getTitle());
                            }

                            if(zhiNengZhiZaoXiangQingEntity.getResponse().getAdd_time() == null){

                            }else{ // 时间
                                tvTime.setText(zhiNengZhiZaoXiangQingEntity.getResponse().getAdd_time());
                            }

                            if(zhiNengZhiZaoXiangQingEntity.getResponse().getContent() == null){

                            }else{ // 内容
                                content = zhiNengZhiZaoXiangQingEntity.getResponse().getContent();
                                webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content),"text/html", "UTF-8", null);
                            }
                        }
                    }
                });
    }



    @OnClick({R.id.image_back, R.id.image_shoucang, R.id.image_fenxiang})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
//            收藏
            case R.id.image_shoucang:
//                收藏的网络请求
                initShouCangHttp();
                break;
//            分享
            case R.id.image_fenxiang:
                //        智能制造分享的网络请求
                initZhiNengZhiZaoHttp();

                
                break;
        }
    }



    private void initShouCangHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"news/shoucang")
                .addHeader("token",ContractUtils.getTOKEN(ZhiNengZhiZaoXiangQingActivity.this))
                .addParams("typeId","1")//0 =>园区手册1 => 智能制造2=>产品金融 3首页园区资讯, 4 政策法规, 5企服中心, 6园区招商
                .addParams("id",wenzhangid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e+"            shoucangeeeeeeeeee");

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ZhiNengZhiZaoXiangQingActivity.this,response);
                        System.out.println(response+"          园区手册收藏的网络请求");

                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            WenZhangShouCangEntity wenZhangShouCangEntity = gson.fromJson(response, WenZhangShouCangEntity.class);
                            Toast.makeText(ZhiNengZhiZaoXiangQingActivity.this, wenZhangShouCangEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            if(wenZhangShouCangEntity.getMsg().equals("收藏成功")){
                                imageShoucang.setImageResource(R.drawable.quxia_shoucang);
                            }else if(wenZhangShouCangEntity.getMsg().equals("取消收藏成功")){
                                imageShoucang.setImageResource(R.drawable.shoucang);
                            }
                        }
                    }
                });
    }



    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {
//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }
}
